package com.kw.model.weixin;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.kw.utils.SHA1;

public class WeiXinInterfaceServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static String token;
	
	public synchronized void init() throws ServletException { 
		token=getServletConfig().getInitParameter("token");
	}
	
	public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
		String signature=request.getParameter("signature") ;
		String timestamp=request.getParameter("timestamp");
		String nonce=request.getParameter("nonce");
		String echostr=request.getParameter("echostr");
		String[] ss={token,timestamp,nonce};
		Arrays.sort(ss);
		String res=ss[0]+ss[1]+ss[2];
	//	res=SHA1.SHA1Digest(res);
		PrintWriter pw=response.getWriter();
		if(res!=null){
			if(res.equals(signature)){
				pw.write(echostr);
				pw.flush();
			}
		}
		pw.close();
	}
	
	public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
		//request.setCharacterEncoding("GBK");
		InputStream is=request.getInputStream();
		SAXParserFactory factory = SAXParserFactory.newInstance(); 
		WeiXinOutputContent wxos=null;
		try {
			SAXParser parser = factory.newSAXParser();
			DefaultHandler dh=new WeiXinXMLHandler();
			parser.parse(is, dh);
			
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
		
	}
	
	public void destroy(){
		
	}

}
